package com.huiztech.kaoqinji;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.AlignmentSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.huiztech.kaoqinji.model.ClientDetail;
import com.huiztech.kaoqinji.photo.ModifyAvatarDialog;
import com.huiztech.util.BMapUtil;
import com.lidroid.xutils.util.LogUtils;

/**
 *
 * @author zhiyuan
 *
 */
public class ClientDetailActivity extends BaseActivity {
    private static final int FLAG_CHOOSE_IMG = 5;
    private static final int FLAG_MODIFY_FINISH = 7;
    private String TAG = "";
    private static String localTempImageFileName = "";
    public static final String IMAGE_PATH = "Kaoqinji";
    public static final File FILE_SDCARD = Environment.getExternalStorageDirectory();
    public static final File FILE_LOCAL = new File(FILE_SDCARD, IMAGE_PATH);
    public static final File FILE_PIC_SCREENSHOT = new File(FILE_LOCAL, "images/screenshots");
    private String path = "";
    private TextView nameText, companyNameText, positionText, bumenText, phoneText, beizhuText, timeText;
    private ImageView imageView;
    private Button visitButton;
    LinearLayout beizhuLayout;
    private int customerId;
    public LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private RelativeLayout.LayoutParams params;
    private LocApplication application;
    private long recLen = 0;
    private Timer timer = new Timer();
    private TimerTask task;
    private SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
    private static final String visitTimeText = "visit_time";
    private static final String visitBtnText = "visit_btn";

    private LinearLayout backLayout;
    private TextView addressText;
    private TextView emailText;
    private TextView QQText;
    private LinearLayout startVisitLayout;
    private LinearLayout stopVisitLayout;
    private ImageView cameraImage;

    private String fileName = "";
    //private String path = "";
    private boolean isCrop = false;
    File tempFile;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client_detail);
        findView();
        initUI();
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        setLocationOption();
        visitButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                requestLocClick();
            }
        });
        backLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (visitButton.getText().toString().equals("结束")) {
                    controller.editor.putLong(visitTimeText, System.currentTimeMillis());
                    controller.editor.putString(visitBtnText, visitButton.getText().toString());
                    controller.editor.putInt("customerId", customerId);
                    controller.editor.commit();
                }
                finish();
            }
        });
        startVisitLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                requestLocClick();
            }
        });
        stopVisitLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (visitButton.getText().toString().equals("开始")) {
                    Toast.makeText(ClientDetailActivity.this, "请先开始拜访", Toast.LENGTH_SHORT).show();
                } else {
                    requestLocClick();
                }
            }
        });
        cameraImage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //photoDialog();
                showDialog();
            }
        });
        //        beizhuLayout.setOnClickListener(new OnClickListener() {
        //            @Override
        //            public void onClick(View v) {
        //
        //            }
        //        });
    }

    public static String getStringToday() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    private void showDialog() {
        new AlertDialog.Builder(ClientDetailActivity.this).setTitle("设置头像")
                .setItems(StaticVariables.items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case 1: // 相册
                            Intent intentFromGallery = new Intent();
                            intentFromGallery.setType("image/*"); // 设置文件类型
                            intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intentFromGallery, StaticVariables.IMAGE_REQUEST_CODE);
                            break;
                        case 0: // 照相
                            fileName = getStringToday() + ".jpg";
                            Intent intentFromCapture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                            intentFromCapture.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(new File(Environment.getExternalStorageDirectory(), fileName)));
                            startActivityForResult(intentFromCapture, StaticVariables.CAMERA_REQUEST_CODE);
                            break;
                        }
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

//    private void photoDialog() {
//        // 调用选择那种方式的dialog
//        ModifyAvatarDialog modifyAvatarDialog = new ModifyAvatarDialog(this) {
//            // 选择本地相册
//            @Override
//            public void doGoToImg() {
//                this.dismiss();
//                Intent intent = new Intent();
//                intent.setAction(Intent.ACTION_PICK);
//                intent.setType("image/*");
//                startActivityForResult(intent, FLAG_CHOOSE_IMG);
//            }
//
//            // 选择相机拍照
//            @Override
//            public void doGoToPhone() {
//                this.dismiss();
//                String status = Environment.getExternalStorageState();
//                if (status.equals(Environment.MEDIA_MOUNTED)) {
//                    try {
//                        localTempImageFileName = "";
//                        localTempImageFileName = String.valueOf((new Date()).getTime()) + ".png";
//                        File filePath = FILE_PIC_SCREENSHOT;
//                        if (!filePath.exists()) {
//                            filePath.mkdirs();
//                        }
//                        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//                        File f = new File(filePath, localTempImageFileName);
//                        // localTempImgDir和localTempImageFileName是自己定义的名字
//                        Uri u = Uri.fromFile(f);
//                        intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
//                        intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
//                        startActivityForResult(intent, 1);
//                    } catch (ActivityNotFoundException e) {
//                        //
//                    }
//                }
//
//            }
//        };
//        AlignmentSpan span = new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER);
//        AbsoluteSizeSpan span_size = new AbsoluteSizeSpan(25, true);
//        SpannableStringBuilder spannable = new SpannableStringBuilder();
//        String dTitle = getString(R.string.gl_choose_title);
//        spannable.append(dTitle);
//        spannable.setSpan(span, 0, dTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        spannable.setSpan(span_size, 0, dTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        modifyAvatarDialog.setTitle(spannable);
//        modifyAvatarDialog.show();
//
//    }

    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setAddrType("all");
        option.setServiceName("com.baidu.location.service_v2.9");
        mLocClient.setLocOption(option);
    }

    /**
     * 手动触发一次定位请求
     */
    public void requestLocClick() {
        mLocClient.start();
        mLocClient.requestLocation();
    }

    /**
     * 定位监听函数
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) return;
            // 判断本地是否存有attendance_id字段 确定是否已经签到





            if (controller.getInfoByLocal(AppConst.SP_ATTENDANCE_KEY, null) != null) {
                // TODO 这里判断不对  应该判断是否与当前界面customer一样
                if (customerId == controller.sp.getInt(AppConst.SP_CUSTOMER_ID_KEY, -1)
                        || controller.sp.getInt(AppConst.SP_CUSTOMER_ID_KEY, -1) == -1) {
                    if (visitButton.getText().toString().equals("开始")) {
                        if(!path.equals("")){
                            LogUtils.i(tempFile+"===========");
                            controller.startVisit(location.getLatitude(), location.getLongitude(), customerId,tempFile);
                            task = new TimerTask() {
                                @Override
                                public void run() {
                                    recLen = recLen + 1000;
                                    application.setVistTime(recLen);
                                    Message message = new Message();
                                    message.what = 1;
                                    handler.sendMessage(message);
                                }
                            };
                            timer.schedule(task, 1000, 1000);
                            visitButton.setText("结束");
                        }else {
                            view.showMessage("请先为客户拍照!");
                        }
//                        path = Environment.getExternalStorageDirectory() + "/" + fileName;
//                        File tempFile = new File(path);

                    } else {
                        controller.stopVisit(location.getLatitude(), location.getLongitude(), customerId);
                        recLen = 0;
                        application.setVistTime(recLen);
                        timeText.setText("" + formatter.format(application.getVisitTime()));
                        task.cancel();
                        visitButton.setText("开始");
                    }
                } else {
                    view.showMessage("请先结束上一次拜访!");
                }
            } else {
                view.showMessage("请先进行签到!");
            }

        }

        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null) {
                return;
            }
        }

    }

    /**
     * 初始化UI
     */
    private void initUI() {
        // 设置头像图片宽高
        //        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        //        int windowsWidth = wm.getDefaultDisplay().getWidth();
        //        int windowsHeight = wm.getDefaultDisplay().getHeight();
        //        int width = (int) (windowsWidth * 0.50); // 宽度
        //        int height = width;// 高度
        //        params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
        //        params.width = width;
        //        params.height = height;
        //        imageView.setLayoutParams(params);

        // 得到客户id
        @SuppressWarnings("unchecked")
        List<ClientDetail> clientDetailList = (List<ClientDetail>) model.get("clientDetail");
        int customerPosition = getIntent().getIntExtra("customerPosition", 0);
        // 设置各个组件显示内容
        customerId = clientDetailList.get(customerPosition).getId();
        nameText.setText(clientDetailList.get(customerPosition).getName());
        companyNameText.setText(clientDetailList.get(customerPosition).getCompanyName());
        positionText.setText(clientDetailList.get(customerPosition).getPosition());
        phoneText.setText(clientDetailList.get(customerPosition).getPhone());
        QQText.setText(clientDetailList.get(customerPosition).getQq());
        emailText.setText(clientDetailList.get(customerPosition).getEmail());
        addressText.setText(clientDetailList.get(customerPosition).getCompanyAddress());
        if (clientDetailList.get(customerPosition).equals("")) {
            imageView.setBackgroundResource(R.drawable.moren);
        } else {
            imageLoader.displayImage(AppConst.KAOQIN_UPLOAD_URL + clientDetailList.get(customerPosition).getImage(),
                    imageView, options);
        }
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        // 如果此次进入界面是开始拜访状态
        if (customerId == controller.sp.getInt(AppConst.SP_CUSTOMER_ID_KEY, -1)) {
            visitButton.setText(controller.sp.getString(visitBtnText, "开始"));
            if (controller.sp.getLong(visitTimeText, 0) != 0) {
                visitButton.setBackgroundResource(R.drawable.visit_start);
                recLen = System.currentTimeMillis() - controller.sp.getLong(visitTimeText, 0)
                        + application.getVisitTime();// 毫秒数
                task = new TimerTask() {
                    @Override
                    public void run() {
                        recLen = recLen + 1000;
                        application.setVistTime(recLen);
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                };
                timer.schedule(task, 1000, 1000);
            }
        }
    }

    private void findView() {
        application = (LocApplication) getApplication();
        visitButton = (Button) findViewById(R.id.client_detail_btn);
        nameText = (TextView) findViewById(R.id.client_detail_name);
        companyNameText = (TextView) findViewById(R.id.client_detail_company);
        positionText = (TextView) findViewById(R.id.client_detail_zhiwei);
        phoneText = (TextView) findViewById(R.id.client_detail_phone);
        imageView = (ImageView) findViewById(R.id.client_detail_image);
        backLayout = (LinearLayout) findViewById(R.id.client_detail_back_layout);
        //beizhuLayout = (LinearLayout) findViewById(R.id.client_detail_addbeizhu_layout);
        timeText = (TextView) findViewById(R.id.client_detail_time_text);
        emailText = (TextView) findViewById(R.id.client_detail_email);
        QQText = (TextView) findViewById(R.id.client_detail_qq);
        addressText = (TextView) findViewById(R.id.client_detail_address_text);
        startVisitLayout = (LinearLayout) findViewById(R.id.client_detail_footprint_start_layout);
        stopVisitLayout = (LinearLayout) findViewById(R.id.client_detail_footprint_stop_layout);
        cameraImage = (ImageView) findViewById(R.id.client_camera_image);
    }

    // 更改UI
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 1:
                timeText.setText("" + formatter.format(application.getVisitTime()));
            }
        }
    };

    // 返回键事件
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (visitButton.getText().toString().equals("结束")) {
                controller.editor.putString(visitBtnText, visitButton.getText().toString());
                controller.editor.putLong(visitTimeText, System.currentTimeMillis());
                controller.editor.putInt("customerId", customerId);
                controller.editor.commit();
            }
            finish();
            return true;
        }
        return super.onKeyDown(event.getKeyCode(), event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != ClientDetailActivity.this.RESULT_CANCELED) {
            switch (requestCode) {
            case StaticVariables.IMAGE_REQUEST_CODE: // 相册
                Uri uri = data.getData();
                if (uri != null) {
                    Cursor cursor = ClientDetailActivity.this.getContentResolver().query(uri,
                            new String[] { MediaStore.Images.Media.DATA }, null, null, null);
                    cursor.moveToFirst();
                    path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    String[] fragments = path.split("/");
                    fileName = fragments[fragments.length - 1];
                    cursor.close();
                }
                startPhotoZoom(data.getData());
                break;
            case StaticVariables.CAMERA_REQUEST_CODE: // 照相
                System.out.println("onActivityResult 照相 ");
                path = Environment.getExternalStorageDirectory() + "/" + fileName;
                tempFile = new File(path);
                startPhotoZoom(Uri.fromFile(tempFile));
                view.showMessage("拍照成功!");
                break;
            case StaticVariables.RESULT_REQUEST_CODE:
                getImageToView(data);
                break;
            }
        }

        //        if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
        //            if (data != null) {
        //                Uri uri = data.getData();
        //                if (!TextUtils.isEmpty(uri.getAuthority())) {
        //                    Cursor cursor = getContentResolver().query(uri, new String[] { MediaStore.Images.Media.DATA },
        //                            null, null, null);
        //                    if (null == cursor) {
        //                        view.showMessage(R.string.ImageNotFound);
        //                        return;
        //                    }
        //                    cursor.moveToFirst();
        //                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        //                    cursor.close();
        //                    Log.i(TAG, "path=" + path);
        //                    Intent intent = new Intent(this, CropImageActivity.class);
        //                    intent.putExtra("path", path);
        //                    startActivityForResult(intent, FLAG_MODIFY_FINISH);
        //                } else {
        //                    Log.i(TAG, "path=" + uri.getPath());
        //                    Intent intent = new Intent(this, CropImageActivity.class);
        //                    intent.putExtra("path", uri.getPath());
        //                    startActivityForResult(intent, FLAG_MODIFY_FINISH);
        //                }
        //            }
        //        } else if (requestCode == 1 && resultCode == RESULT_OK) {
        //            File f = new File(FILE_PIC_SCREENSHOT, localTempImageFileName);
        //            Intent intent = new Intent(this, CropImageActivity.class);
        //            intent.putExtra("path", f.getAbsolutePath());
        //            startActivityForResult(intent, FLAG_MODIFY_FINISH);
        //
        //        } else if (requestCode == FLAG_MODIFY_FINISH && resultCode == RESULT_OK) {
        //            if (data != null) {
        //                path = data.getStringExtra("path");
        //                Log.i(TAG, "截取到的图片路径是 = " + path);
        //                Bitmap b = BitmapFactory.decodeFile(path);
        //                cameraImage.setImageBitmap(b);
        //
        //            }
        //        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, StaticVariables.RESULT_REQUEST_CODE);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void getImageToView(Intent data) {
        Bundle extras = data.getExtras();
        Bitmap photo = extras.getParcelable("data");
        BMapUtil.saveBitmap2file(photo, fileName);
        if (extras != null) {
            isCrop = true;
        }
    }
}
